package com.hex.tcpproxy.process;

import com.hex.tcpproxy.util.ProxyHandler;
import com.hex.tcpproxy.util.ProxyServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: [wujie]
 * @createTime: [2019/10/8 16:37]
 * @description:
 */

public class MainServer implements Runnable {
    private final static Logger logger = LoggerFactory.getLogger(MainServer.class);
    private Integer port;
    private ProxyHandler proxyHandler;
    private Map<String, FakeServer> fakeServerMap = new ConcurrentHashMap<>();

    public MainServer(int port) {
        this.port = port;
    }


    @Override
    public void run() {
        proxyHandler = new ProxyHandler() {
            @Override
            public void read(String address, byte[] bytes) {
                processData(bytes);
            }
        };
        ProxyServer server = new ProxyServer(port, proxyHandler);
        server.bind();
    }

    private void processData(byte[] bytes) {

        DataExplain dataExplain = new DataExplain(bytes);
        if ("F".equals(dataExplain.getCmd())) {

        } else if ("W".equals(dataExplain.getCmd())) {
            String address = DataExplain.getAddressString(dataExplain.getPara());
            logger.info("从{}收到消息:{}", address, new String(dataExplain.getRealData()));
            fakeServerMap.get(address);
        }
    }

    public void createLine(int port, String address) {
        FakeServer fakeServer = new FakeServer(port, address, this);
        Thread thread = new Thread(fakeServer);
        thread.start();
        fakeServerMap.put(address, fakeServer);
        byte[] addressBytes = DataExplain.getAddressBytes(address);
        DataExplain dataExplain = new DataExplain("O", addressBytes, null);
        proxyHandler.writeAll(dataExplain.getData());
    }

    public void closeLine(String address) {
        FakeServer fakeServer = fakeServerMap.remove(address);
        fakeServer.close();
        byte[] addressBytes = DataExplain.getAddressBytes(fakeServer.getRemoteAdress());
        DataExplain dataExplain = new DataExplain("C", addressBytes, null);
        proxyHandler.writeAll(dataExplain.getData());
    }

    public void sendData(byte[] bytes) {
        proxyHandler.writeAll(bytes);
    }


}
